<?php


namespace App\Models\OpenShop\SiteLocation;


use App\Enums\OpenShop\InvestmentPromotion\SiteLocationEnum;
use App\Enums\OpenShop\InvestmentPromotion\UploadFileResourceEnum;
use App\Models\BaseModel;
use App\Models\OpenShop\Common\OpenShopOrderManagerModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopLocationModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopMainProcessModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopOrganizationManageModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSignOrderModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopUploadFileResourceModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopUserBaseInfoModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopUserContractModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopUserIdentityCardModel;
use App\Models\Traits\KfSoftDeletes;
use App\Models\Traits\KfUid;
use App\Service\Common\AreaService;
use App\Service\Kms\Home\HomeService;
use App\Service\OpenShop\SiteLocation\SiteLocationInputService;
use App\Service\OpenShop\Wap\SignOrderService;
use App\Service\Rms\ShopService;
use DateTimeInterface;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Database\Eloquent\Relations\HasOneThrough;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Cache;

class OpenShopSiteLocationModel extends BaseModel
{
    use KfUid;
    use KfSoftDeletes;

    protected $table = 'open_shop_site_locations';

    protected $fillable = [
        'id',
        'orderNo',
        'source',
        'mainProcessId',
        'messageFrom',
        'shopPattern',
        'patternType',
        'longitude',
        'placeholderTime',
        'latitude',
        'siteAddress',
        'cityArea',
        'cityType',
        'address',
        'selectTime',
        'currentFormat',
        'operatingStatus',
        'leaseStatus',
        'driveType',
        'siteType',
        'flowLine',
        'orientation',
        'yinYangJie',
        'visualLabel',
        'streetLength',
        'decorationShopType',
        'doorWidth',
        'doorHeadWidth',
        'shopWidth',
        'floorHeight',
        'depth',
        'area',
        'electricityConsumption',
        'isCapacityIncrease',
        'capacityIncreaseFee',
        'exhaustAirVolume',
        'isExhaustReconstruction',
        'upperWaterDiameter ',
        'lowerWaterDiameter ',
        'isReformWater ',
        'airConditionerCType ',
        'isFireControl',
        'adSpaceNumber',
        'rentType',
        'fixedRent',
        'remind',
        'rentPaymentCycle',
        'deposit',
        'leaseTerm',
        'rentFreePeriod',
        'waterFee',
        'electricityFee',
        'propertyFee',
        'mobilizationMobile',
        'mobilizationFee',
        'mobilizationFeeDesc',
        'bond',
        'manageFee',
        'sponsorshipFee',
        'promotionFee',
        'otherFee',
        'otherFeeDesc',
        'leaseMobile',
        'leaseName',
        'leaseWeChat',
        'businessStrategy',
        'caseRegisterType',
        'restrictedSales',
        'siteAdvantage',
        'siteInferiority',
        'openTime',
        'status',
        'isDeleted',
        'createdAt',
        'updatedAt',
        'createdByUid',
        'updatedByUid',
        'deposit',
        'provinceCode',
        'cityCode',
        'areaCode',
        'developConsultantName',
        'developConsultantId',
        'siteStatus',
        'chooseShopProvinceCode',
        "cityCode",
        "areaCode",
        "merchantConfirmTime",
        'houseEvaluateStatus',
        'score',
        'grade',
        'shopGrade',
        'clueStatus',
        'wallTailUsedOld',
        'rentGrade',
        'clueRent',
        "mallId",
        "mallName",
        "mallGrade",
        "mallStatus",
        "isWhiteList",
        "isAuditMall",
        "mallProvince",
        "mallCity",
        "mallDistrict",
        "mallArea",
        "mallAddress",
        "shopTotalNum",
        "goShoppingNum",
        "gourmetShopNum",
        "gourmetShopRatio",
        "star",
        "facilitiesRating",
        "environmentRating",
        "serviceRating",
        "nearbyPlaceHolderRange",
        "nearbyPlaceHolderId",
        "placeholderTime",
        "businessMap",
        "businessDistrict",
        "businessArea",
        "businessAddress",
        "signatureTime",
        "ctRentType",
        "ctFixedRent",
        "ctRemind",
        "ctRentPaymentCycle",
        "ctDeposit",
        "ctLeaseTerm",
        "ctRentFreePeriod",
        "ctPropertyFee",
        "ctMobilizationFee",
        "ctTransferFee",
        "ctBond",
        "ctManageFee",
        "ctSponsorshipFee",
        "ctPromotionFee",
        "ctOtherFee",
        "leaseFiles",
        "transferFee",
        "ctSubmitTime",
        "developConsultantFlagNotice",
        "handler",
        "blongFloor",
        "jsonField",
        'shopType',
        'siteSelection',
        'sellingCategory',
        'menuLevel',
        'posLine',
        'warehouseFixedRent',
        'warehouseRentPaymentCycle',
        'warehouseDeposit',
        'warehouseLeaseTerm',
        'warehouseRentFreePeriod',
        'doubleWaimai',
        'douyin',
        'franchiseesKnow',
        'shopFacadeType',
        'openDoorType',
        'isChangeDoor',
    ];


    //设置json字段
    const JSON_FIELD = [
        'ctStartTime',
        'ctEndTime',
    ];


    const SITE_STATUS_0 = 0;
    const SITE_STATUS_1 = 1;
    const SITE_STATUS_2 = 2;
    const SITE_STATUS_3 = 3;
    const SITE_STATUS_4 = 4;
    //用于区分省区总
    const SITE_STATUS_5 = 5;

    const SITE_STATUS_10 = 10;   //待审批  待省总审核
    const SITE_STATUS_11 = 11;   //待审核  待总部负责人审核

    const SITE_STATUS_20 = 20;  //商家待确认
    const SITE_STATUS_21 = 21;  //合同待上传
    const SITE_STATUS_22 = 22;  //合同待审批

    const PLACEHOLDER_SITE_STATUS_TEXT = [
        self::SITE_STATUS_0  => '未申请',
        self::SITE_STATUS_3  => '待修改',
        self::SITE_STATUS_4  => '已完成',
        self::SITE_STATUS_10 => '待省总审核',
        self::SITE_STATUS_11 => '待总部审核',
    ];

    const CN_STATUS = [
        self::SITE_STATUS_0  => '待选址',
        self::SITE_STATUS_1  => '待提交',
        //self::SITE_STATUS_2 => '已提交',
        self::SITE_STATUS_2  => '待审批',
        self::SITE_STATUS_3  => '待修改',
        self::SITE_STATUS_4  => '已完成',
        self::SITE_STATUS_11 => '待审核',
        self::SITE_STATUS_10 => '待审批',
        self::SITE_STATUS_20 => '商家待确认',
        self::SITE_STATUS_21 => '合同待上传',
        self::SITE_STATUS_22 => '合同待审批',
    ];

    const CN_PROVINCE_STATUS = [
        self::SITE_STATUS_0  => '待选址',
        self::SITE_STATUS_1  => '待提交',
        self::SITE_STATUS_2  => '待审批',
        //self::SITE_STATUS_2 => '已提交',
        //self::SITE_STATUS_3 => '待审批',
        self::SITE_STATUS_3  => '待修改',
        self::SITE_STATUS_4  => '已完成',
        self::SITE_STATUS_11 => '待审核',
        self::SITE_STATUS_10 => '待审批',
        self::SITE_STATUS_20 => '商家待确认',
        self::SITE_STATUS_21 => '合同待上传',
        self::SITE_STATUS_22 => '合同待审批',
    ];

    //选址来源
    const SOURCE_OPEN_SHOP   = 0;
    const SOURCE_HOUSING     = 1;
    const SOURCE_PLACEHOLDER = 2;
    const SOURCE_MAP         = [
        self::SOURCE_OPEN_SHOP   => "开店",
        self::SOURCE_HOUSING     => "房源",
        self::SOURCE_PLACEHOLDER => "预占址",
    ];

    const CLUE_STATUS_0   = 0; //已关闭
    const CLUE_STATUS_1   = 1; //线索待分配
    const CLUE_STATUS_2   = 2; //已分配待考擦
    const CLUE_STATUS_3   = 3; //已考察待审批
    const CLUE_STATUS_4   = 4; //审批不通过待修改
    const CLUE_STATUS_5   = 5; //已上架
    const CLUE_STATUS_6   = 6; //已成交
    const CLUE_STATUS_10  = 10;//已下架
    const CLUE_STATUS_11  = 11;//待审核
    const CLUE_STATUS_12  = 12;//待自评
    const CLUE_STATUS_13  = 13;//待评估
    const CLUE_STATUS_MAP = [
        self:: CLUE_STATUS_0  => "已关闭",
        self:: CLUE_STATUS_1  => "待分配",
        self:: CLUE_STATUS_2  => "房源线索",
        self:: CLUE_STATUS_3  => "待审批",
        self:: CLUE_STATUS_4  => "待修改",
        self:: CLUE_STATUS_5  => "已上架",
        self:: CLUE_STATUS_6  => "已成交",
        self:: CLUE_STATUS_10 => "已下架",
        self:: CLUE_STATUS_11 => "待审核",
        self:: CLUE_STATUS_12 => "待自评",
        self:: CLUE_STATUS_13 => "待评估",
    ];

    const SITE_LOCATION_CLUE_MAPPING = [
        self:: CLUE_STATUS_0  => "已完成",
        self:: CLUE_STATUS_1  => "待选址",
        self:: CLUE_STATUS_2  => "待选址",
        self:: CLUE_STATUS_3  => "待审批",
        self:: CLUE_STATUS_4  => "待修改",
        self:: CLUE_STATUS_5  => "已完成",
        self:: CLUE_STATUS_6  => "已完成",
        self:: CLUE_STATUS_10 => "已完成",
        self:: CLUE_STATUS_11 => "待审核",
        self:: CLUE_STATUS_12 => "待选址",
        self:: CLUE_STATUS_13 => "待选址",
    ];

    const CITY_AREA_ARRAY_INDEX_0 = 0;
    const CITY_AREA_ARRAY_INDEX_1 = 1;
    const CITY_AREA_ARRAY_INDEX_2 = 2;

    //默认未绑定值
    const SITE_LOCATION_BIND_FALSE = 0;

    const HOUSE_CLUE_MYSELF = 0;//我的房源
    const HOUSE_CLUE_ALL    = 1;//所有房源（上架房源）

    const HOUSE_SHOP_GRADE_S       = 6;
    const HOUSE_SHOP_GRADE_A       = 5;
    const HOUSE_SHOP_GRADE_B       = 4;
    const HOUSE_SHOP_GRADE_C       = 3;
    const HOUSE_SHOP_GRADE_D       = 2;
    const HOUSE_SHOP_GRADE_E       = 1;
    const HOUSE_SHOP_GRADE_DEFAULT = 0;

    //用于筛选
    const HOUSE_SHOP_GRADE_SIFT_MAPPING = [
        self::HOUSE_SHOP_GRADE_S => 'S级',
        self::HOUSE_SHOP_GRADE_A => 'A级',
        self::HOUSE_SHOP_GRADE_B => 'B级',
        self::HOUSE_SHOP_GRADE_C => 'C级',
        self::HOUSE_SHOP_GRADE_D => 'D级',
        self::HOUSE_SHOP_GRADE_E => 'E级',
        //self::HOUSE_SHOP_GRADE_DEFAULT    => '',   //默认等级  为空为了兼容老数据 「前端不展示」
    ];

    const HOUSE_GRADE_QUESTION   = 1;
    const HOUSE_GRADE_SKINNY_DOG = 2;
    const HOUSE_GRADE_TAURUS     = 3;
    const HOUSE_GRADE_STAR       = 4;

    //用于筛选
    const HOUSE_GRADE_SIFT_MAPPING = [
        self::HOUSE_GRADE_QUESTION   => '问题',
        self::HOUSE_GRADE_SKINNY_DOG => '瘦狗',
        self::HOUSE_GRADE_TAURUS     => '金牛',
        self::HOUSE_GRADE_STAR       => '明星',
    ];

    const HOUSE_RENT_LESS_THAN_TWO              = 1;
    const HOUSE_RENT_BETWEEN_TWO_AND_THREE      = 2;
    const HOUSE_RENT_BETWEEN_THREE_AND_SIX      = 3;
    const HOUSE_RENT_BETWEEN_SIX_AND_TEN        = 4;
    const HOUSE_RENT_BETWEEN_TEN_AND_FIFTEEN    = 5;
    const HOUSE_RENT_BETWEEN_FIFTEEN_AND_TWENTY = 6;
    const HOUSE_RENT_GREATER_THAN_TWENTY        = 7;

    //用于筛选
    const HOUSE_RENT_SIFT_MAPPING = [
        self::HOUSE_RENT_LESS_THAN_TWO              => '小于2万',
        self::HOUSE_RENT_BETWEEN_TWO_AND_THREE      => '2万至3万',
        self::HOUSE_RENT_BETWEEN_THREE_AND_SIX      => '3万至6万',
        self::HOUSE_RENT_BETWEEN_SIX_AND_TEN        => '6万至10万',
        self::HOUSE_RENT_BETWEEN_TEN_AND_FIFTEEN    => '10万至15万',
        self::HOUSE_RENT_BETWEEN_FIFTEEN_AND_TWENTY => '15万至20万',
        self::HOUSE_RENT_GREATER_THAN_TWENTY        => '大于20万',
    ];

    //用于组建SQL=>ORM
    const HOUSE_RENT_ORM_MAPPING = [
        self::HOUSE_RENT_LESS_THAN_TWO              => [0, 2000000],
        self::HOUSE_RENT_BETWEEN_TWO_AND_THREE      => [2000000, 3000000],
        self::HOUSE_RENT_BETWEEN_THREE_AND_SIX      => [3000000, 6000000],
        self::HOUSE_RENT_BETWEEN_SIX_AND_TEN        => [6000000, 10000000],
        self::HOUSE_RENT_BETWEEN_TEN_AND_FIFTEEN    => [10000000, 15000000],
        self::HOUSE_RENT_BETWEEN_FIFTEEN_AND_TWENTY => [15000000, 20000000],
        self::HOUSE_RENT_GREATER_THAN_TWENTY        => 20000000,  //比较特殊  if(A==this) => 特殊处理
    ];


    const HOUSE_GROUP_BY_UNIT_PRICE_ASC  = 1;
    const HOUSE_GROUP_BY_UNIT_PRICE_DESC = 2;
    const HOUSE_GROUP_BY_RENT_ASC        = 3;
    const HOUSE_GROUP_BY_RENT_DESC       = 4;
    const HOUSE_GROUP_BY_AREA_ASC        = 5;
    const HOUSE_GROUP_BY_AREA_DESC       = 6;

    //用于筛选
    const HOUSE_GROUP_BY_SIFT_MAPPING = [
        self::HOUSE_GROUP_BY_UNIT_PRICE_ASC  => '单价从低到高',  //租金/面积
        self::HOUSE_GROUP_BY_UNIT_PRICE_DESC => '单价从高到低',
        self::HOUSE_GROUP_BY_RENT_ASC        => '房租从低到高',
        self::HOUSE_GROUP_BY_RENT_DESC       => '房租从高到低',
        self::HOUSE_GROUP_BY_AREA_ASC        => '面积从小到大',
        self::HOUSE_GROUP_BY_AREA_DESC       => '面积从大到小',
    ];

    const HOUSE_AREA_LESS_THAN_TWENTY               = 1;
    const HOUSE_AREA_BETWEEN_TWENTY_AND_THIRTY_FIVE = 2;
    const HOUSE_AREA_BETWEEN_THIRTY_FIVE_AND_FIFTY  = 3;
    const HOUSE_AREA_GREATER_THAN_FIFTY             = 4;

    //用于筛选
    const HOUSE_AREA_SIFT_MAPPING = [
        self::HOUSE_AREA_LESS_THAN_TWENTY               => '小于20㎡',
        self::HOUSE_AREA_BETWEEN_TWENTY_AND_THIRTY_FIVE => '20㎡至35㎡',
        self::HOUSE_AREA_BETWEEN_THIRTY_FIVE_AND_FIFTY  => '35㎡至50㎡',
        self::HOUSE_AREA_GREATER_THAN_FIFTY             => '大于50㎡',
    ];

    //用于组建SQL=>ORM
    const HOUSE_AREA_ORM_MAPPING = [
        self::HOUSE_AREA_LESS_THAN_TWENTY               => [0, 20],
        self::HOUSE_AREA_BETWEEN_TWENTY_AND_THIRTY_FIVE => [20, 35],
        self::HOUSE_AREA_BETWEEN_THIRTY_FIVE_AND_FIFTY  => [35, 50],
        self::HOUSE_AREA_GREATER_THAN_FIFTY             => 50,
    ];


    const HOUSE_OPERATE_TYPE_DELETE = 1;  //删除
    const HOUSE_OPERATE_TYPE_LOSE   = 2;  //失效


    /**
     * 门店模式
     */
    const SHOP_PATTERN_TWO   = 2;
    const SHOP_PATTERN_THREE = 3;

    const SHOP_PATTERN_MAPPING = [
        self::SHOP_PATTERN_TWO   => '二代店',
        self::SHOP_PATTERN_THREE => '叁代店',
    ];

    // 临时的按钮选择 （舍弃叁代店）
    const TEMP_SHOP_PATTERN_MAPPING = [
        self::SHOP_PATTERN_TWO   => '二代店',
        //self::SHOP_PATTERN_THREE => '叁代店',
    ];


    /**
     * 模式分类
     */
    const PATTERN_TYPE_SKEWER      = 1;
    const PATTERN_TYPE_CHICKEN     = 2;
    const PATTERN_TYPE_DRINK       = 3;
    const PATTERN_TYPE_STINKY_TOFU = 4;
    const PATTERN_TYPE_STEAMED_BUN = 5;
    const PATTERN_TYPE_MAPPING = [
        self::PATTERN_TYPE_SKEWER      => '炸串',
        self::PATTERN_TYPE_CHICKEN     => '炸鸡',
        self::PATTERN_TYPE_DRINK       => '饮品',
        self::PATTERN_TYPE_STINKY_TOFU => '臭豆腐',
        self::PATTERN_TYPE_STEAMED_BUN => '布袋馍',
    ];

    const PATTERN_TYPE_MAPPING_BY_PATTERN_TWO = [
        self::PATTERN_TYPE_SKEWER      => '炸串',
        self::PATTERN_TYPE_STINKY_TOFU => '臭豆腐',
        self::PATTERN_TYPE_STEAMED_BUN => '布袋馍',
    ];

    const PATTERN_TYPE_MAPPING_BY_PATTERN_THREE = [
        self::PATTERN_TYPE_SKEWER      => '炸串',
        self::PATTERN_TYPE_CHICKEN     => '炸鸡',
        self::PATTERN_TYPE_DRINK       => '饮品',
        self::PATTERN_TYPE_STINKY_TOFU => '臭豆腐',
        self::PATTERN_TYPE_STEAMED_BUN => '布袋馍',
    ];


    /**
     * 通过patternType获得中文描述
     * @param $patternType
     * @return string
     */
    public static function getPatternTypeStr($patternType): string
    {
        if (!$patternType) {
            return '';
        }
        $patternTypeArr = Arr::sort(explode(',', $patternType));
        return collect($patternTypeArr)->map(function ($patternItem) {
            return self::PATTERN_TYPE_MAPPING[$patternItem] ?? null;
        })->filter()->implode('+');
    }


    // 运营app-选址tab-房源
    const CLUE_SEARCH_STATUS_1   = 1; //已上架房源
    const CLUE_SEARCH_STATUS_2   = 2; //线索待完善
    const CLUE_SEARCH_STATUS_3   = 3; //线索待分配
    const CLUE_SEARCH_STATUS_4   = 4; //线索待审批
    const CLUE_SEARCH_STATUS_5   = 5; //线索待修改
    const CLUE_SEARCH_STATUS_6   = 6; //线索已关闭
    const CLUE_SEARCH_STATUS_7   = 7; //成交/下架房源

    const CLUE_SEARCH_STATUS_MAP = [
        self::CLUE_SEARCH_STATUS_1 => "已上架房源",
        self::CLUE_SEARCH_STATUS_2 => "线索待完善",
        self::CLUE_SEARCH_STATUS_3 => "线索待分配",
        self::CLUE_SEARCH_STATUS_4 => "线索待审批",
        self::CLUE_SEARCH_STATUS_5 => "线索待修改",
        self::CLUE_SEARCH_STATUS_6 => "线索已关闭",
        self::CLUE_SEARCH_STATUS_7 => "成交/下架房源",
    ];

    const CLUE_SEARCH_STATUS_VALUE_MAP = [
        self::CLUE_SEARCH_STATUS_1 => [self::CLUE_STATUS_5],                                                                                                           //已上架房源
        self::CLUE_SEARCH_STATUS_2 => [OpenShopSiteLocationModel::CLUE_STATUS_12, OpenShopSiteLocationModel::CLUE_STATUS_2, OpenShopSiteLocationModel::CLUE_STATUS_13],//线索待完善
        self::CLUE_SEARCH_STATUS_3 => [self::CLUE_STATUS_1],                                                                                                           //线索待分配
        self::CLUE_SEARCH_STATUS_4 => [OpenShopSiteLocationModel::CLUE_STATUS_3, OpenShopSiteLocationModel::CLUE_STATUS_11],                                           //线索待审批
        self::CLUE_SEARCH_STATUS_5 => [self::CLUE_STATUS_4],                                                                                                           //线索待修改
        self::CLUE_SEARCH_STATUS_6 => [self::CLUE_STATUS_0],                                                                                                           //线索已关闭
        self::CLUE_SEARCH_STATUS_7 => [self::CLUE_STATUS_6, self::CLUE_STATUS_10],                                                                                     //成交/下架房源
    ];

    //用于筛选
    const HOUSE_SEARCH_RENT_SIFT_MAPPING = [
        self::HOUSE_RENT_LESS_THAN_TWO              => '5K以下',
        self::HOUSE_RENT_BETWEEN_TWO_AND_THREE      => '5K-10K',
        self::HOUSE_RENT_BETWEEN_THREE_AND_SIX      => '10K-15K',
        self::HOUSE_RENT_BETWEEN_SIX_AND_TEN        => '15K-20K',
        self::HOUSE_RENT_GREATER_THAN_TWENTY        => '20K以上',
    ];

    //用于组建SQL=>ORM
    const HOUSE_SEARCH_RENT_ORM_MAPPING = [
        self::HOUSE_RENT_LESS_THAN_TWO              => [0, 500000],
        self::HOUSE_RENT_BETWEEN_TWO_AND_THREE      => [500000, 1000000],
        self::HOUSE_RENT_BETWEEN_THREE_AND_SIX      => [1000000, 1500000],
        self::HOUSE_RENT_BETWEEN_SIX_AND_TEN        => [1500000, 2000000],
        self::HOUSE_RENT_GREATER_THAN_TWENTY        => 2000000,  //比较特殊  if(A==this) => 特殊处理
    ];

    //用于筛选
    const HOUSE_SEARCH_AREA_SIFT_MAPPING = [
        self::HOUSE_AREA_LESS_THAN_TWENTY               => '1-15㎡',
        self::HOUSE_AREA_BETWEEN_TWENTY_AND_THIRTY_FIVE => '15-30㎡',
        self::HOUSE_AREA_BETWEEN_THIRTY_FIVE_AND_FIFTY  => '30-50㎡',
        self::HOUSE_AREA_GREATER_THAN_FIFTY             => '50㎡以上',
    ];

    //用于组建SQL=>ORM
    const HOUSE_SEARCH_AREA_ORM_MAPPING = [
        self::HOUSE_AREA_LESS_THAN_TWENTY               => [1, 15],
        self::HOUSE_AREA_BETWEEN_TWENTY_AND_THIRTY_FIVE => [15, 30],
        self::HOUSE_AREA_BETWEEN_THIRTY_FIVE_AND_FIFTY  => [30, 50],
        self::HOUSE_AREA_GREATER_THAN_FIFTY             => 50,
    ];

    //用于筛选
    const HOUSE_SEARCH_GROUP_BY_SIFT_MAPPING = [
        self::HOUSE_GROUP_BY_RENT_ASC        => '房租最低',
        self::HOUSE_GROUP_BY_RENT_DESC       => '房租最高',
        self::HOUSE_GROUP_BY_AREA_ASC        => '面积最小',
        self::HOUSE_GROUP_BY_AREA_DESC       => '面积最大',
    ];

    /**
     * openDoorType 铺位开门形式
     */
    const OPEN_DOOR_TYPE_DEFAULT = 0;
    const OPEN_DOOR_TYPE_GLASS   = 1;
    const OPEN_DOOR_TYPE_ROLL    = 2;
    const OPEN_DOOR_TYPE_OTHER   = 3;

    const OPEN_DOOR_TYPES = [
        self::OPEN_DOOR_TYPE_GLASS => '玻璃门',
        self::OPEN_DOOR_TYPE_ROLL  => '卷帘门',
        self::OPEN_DOOR_TYPE_OTHER => '其他门',
    ];

    /**
     * isChangeDoor 是否可改为玻璃开门
     */
    const IS_CHANGE_DOOR_DEFAULT = 0;
    const IS_CHANGE_DOOR_ON      = 1;
    const IS_CHANGE_DOOR_OFF     = 2;

    const IS_CHANGE_DOOR_MAPPING = [
        self::IS_CHANGE_DOOR_ON  => '是',
        self::IS_CHANGE_DOOR_OFF => '否',
    ];



    /**
     * 根据score计算grade
     * @param int $score
     * @return int
     */
    public static function calcGrade(int $score): int
    {
        if ($score >= 0 && $score < 40) {
            return self::HOUSE_GRADE_QUESTION;
        } elseif ($score >= 40 && $score < 60) {
            return self::HOUSE_GRADE_SKINNY_DOG;
        } elseif ($score >= 60 && $score < 75) {
            return self::HOUSE_GRADE_TAURUS;
        } elseif ($score >= 75) {
            return self::HOUSE_GRADE_STAR;
        } else {
            return self::HOUSE_GRADE_QUESTION;
        }
    }


    /**
     * 根据score计算grade
     * @param int $score
     * @param $rentGrade
     * @return int
     */
    public static function calcShopGrade(int $score, $rentGrade): int
    {
        if ($score >= 0 && $score < 40) {
            //问题
            switch ($rentGrade) {
                case SiteLocationEnum::COST_PERFORMANCE_HIGH:
                    return self::HOUSE_SHOP_GRADE_C;
                case SiteLocationEnum::COST_PERFORMANCE_MEDIUM:
                    return self::HOUSE_SHOP_GRADE_D;
                default:
                    return self::HOUSE_SHOP_GRADE_E;
            }
        } elseif ($score >= 40 && $score < 60) {
            //瘦狗
            switch ($rentGrade) {
                case SiteLocationEnum::COST_PERFORMANCE_HIGH:
                    return self::HOUSE_SHOP_GRADE_B;
                case SiteLocationEnum::COST_PERFORMANCE_MEDIUM:
                    return self::HOUSE_SHOP_GRADE_C;
                default:
                    return self::HOUSE_SHOP_GRADE_D;
            }
        } elseif ($score >= 60 && $score < 75) {
            //金牛
            switch ($rentGrade) {
                case SiteLocationEnum::COST_PERFORMANCE_HIGH:
                    return self::HOUSE_SHOP_GRADE_A;
                case SiteLocationEnum::COST_PERFORMANCE_MEDIUM:
                    return self::HOUSE_SHOP_GRADE_B;
                default:
                    return self::HOUSE_SHOP_GRADE_C;
            }
        } elseif ($score >= 75) {
            //明星
            switch ($rentGrade) {
                case SiteLocationEnum::COST_PERFORMANCE_HIGH:
                    return self::HOUSE_SHOP_GRADE_S;
                case SiteLocationEnum::COST_PERFORMANCE_MEDIUM:
                    return self::HOUSE_SHOP_GRADE_A;
                default:
                    return self::HOUSE_SHOP_GRADE_B;
            }
        } else {
            return self::HOUSE_SHOP_GRADE_E;
        }
    }

    public function getGradeTextAttribute(): string
    {
        return self::HOUSE_GRADE_SIFT_MAPPING[$this->grade] ?? '';
    }

    protected function serializeDate(DateTimeInterface $date)
    {
        return $date->format("Y-m-d H:i:s");
    }

    public function customerAnalysisRel()
    {
        return $this->hasMany(OpenShopSiteLocationCustomerAnalysisModel::class, 'siteId', 'id');
    }

    public function examineLogsRel()
    {
        return $this->hasMany(OpenShopSiteLocationExamineLogModel::class, 'orderNo', 'orderNo');
    }

    public function productAnalysisRel()
    {
        return $this->hasMany(OpenShopSiteLocationProductAnalysisModel::class, 'siteId', 'id');
    }

    public function competingProductsAnalysisRel()
    {
        return $this->hasMany(OpenShopSiteLocationProductAnalysisModel::class, 'siteId', 'id');
    }

    public function complementProductsAnalysisRel()
    {
        return $this->hasMany(OpenShopSiteLocationProductAnalysisModel::class, 'siteId', 'id');
    }

    public static function getSiteForm($siteId)
    {
        try {
            //更新附近预占点位
            (new SiteLocationInputService((string)OpenShopSiteLocationModel::query()->where('id', $siteId)
                                                                           ->value('orderNo')))->updateNearbyPlaceHolder();
        } catch (\Exception $exception) {

        }
        return self::query()
                   ->where('id', $siteId)
                   ->withoutGlobalScope("isDel")
                   //->where('isDeleted', 0)
                   ->with([
                       'customerAnalysisRel' => function ($query) {
                           $query->with([
                               'fileRel' => function ($fileQuery) {
                                   $fileQuery->where('isDeleted', 0)
                                             ->whereIn(
                                                 'position',
                                                 UploadFileResourceEnum::CUSTOMER_ANALYSIS_LIST
                                             );
                               }
                           ])->where('isDeleted', 0);
                       }
                   ])
                   ->with([
                       'productAnalysisRel' => function ($query) {
                           $query->with([
                               'fileRel' => function ($fileQuery) {
                                   $fileQuery->where('isDeleted', 0)
                                             ->whereIn('position', UploadFileResourceEnum::PRODUCT_ANALYSIS_LIST);
                               }
                           ])->where('isDeleted', 0);
                       }
                   ])
                   ->with([
                       'uploadFileResourceRel' => function ($query) {
                           $query->where('isDeleted', 0)
                                 ->whereIn('position', UploadFileResourceEnum::SITE_LOCATION_LIST);
                       }
                   ])
                   ->first();
    }


    /**
     * @param string $orderNo
     * @param string $managerName
     * @param int $managerId
     * @param int $mainProcessId
     * @param int $operateUid
     */
    public static function shopLocationManagerInitOrUpdate(
        string $orderNo,
        string $managerName,
        int $managerId,
        int $mainProcessId,
        int $operateUid = 0,
        bool $resetCreatedInfo = false
    ) {
        $location = self::query()
                        ->whereIn(
                            'source',
                            [
                                OpenShopSiteLocationModel::SOURCE_OPEN_SHOP,
                                OpenShopSiteLocationModel::SOURCE_HOUSING
                            ]
                        )
                        ->where("orderNo", $orderNo)
                        ->first();
        if ($location) {
            $updateData = [
                "updatedAt"             => time(),
                "updatedByUid"          => $operateUid,
                "developConsultantName" => $managerName,
                "developConsultantId"   => $managerId,
                "handler"               => $managerId,
            ];
            self::query()->where("orderNo", $orderNo)->withoutGlobalScope('isDel')->update($updateData);
        } else {
            $baseInfo = OpenShopUserBaseInfoModel::query()->where("orderNo", $orderNo)->first();
            //城市等级
            if ($resetCreatedInfo && $operateUid == 14) {
                $operateUid = 0;
            }
            $grade = AreaService::getCityGradeByCityCode($baseInfo->chooseShopCityCode);
            self::query()->insert([
                "orderNo"                => $orderNo,
                "mainProcessId"          => $mainProcessId,
                "chooseShopProvinceCode" => $baseInfo ? $baseInfo->chooseShopProvinceCode : "",
                "cityArea"               => $baseInfo ? $baseInfo->chooseShopAddressPrefix : "",
                "createdAt"              => time(),
                "updatedAt"              => time(),
                "createdByUid"           => $operateUid,
                "updatedByUid"           => $operateUid,
                "developConsultantName"  => $managerName,
                "developConsultantId"    => $managerId,
                "handler"                => $managerId,
                "cityType"               => $grade['grade'],
                "provinceCode"           => $baseInfo ? $baseInfo->chooseShopProvinceCode : 0,
                "cityCode"               => $baseInfo ? $baseInfo->chooseShopCityCode : 0,
                "areaCode"               => $baseInfo ? $baseInfo->chooseShopDistrictCode : 0,
            ]);
        }
    }


    public function signOrderRel()
    {
        return $this->hasOne(OpenShopSignOrderModel::class, 'orderNo', 'orderNo');
    }

    public function mainProcessRel()
    {
        return $this->hasOne(OpenShopMainProcessModel::class, 'orderNo', 'orderNo');
    }

    public function setStatusOk(int $uid, $siteStatus = OpenShopSiteLocationModel::SITE_STATUS_20)
    {
        $this->status       = SiteLocationEnum::STATUS_1;
        $this->siteStatus   = $siteStatus;
        $this->updatedByUid = $uid;
        if ($siteStatus == OpenShopSiteLocationModel::SITE_STATUS_20) {  //重置合同信息
            $this->signatureTime      = 0;
            $this->ctRentType         = '';
            $this->ctFixedRent        = 0;
            $this->ctRemind           = 0;
            $this->ctRentPaymentCycle = 0;
            $this->ctDeposit          = '';
            $this->ctLeaseTerm        = '';
            $this->ctRentFreePeriod   = '';
            $this->ctPropertyFee      = '';
            $this->ctMobilizationFee  = '';
            $this->ctTransferFee      = '';
            $this->ctBond             = '';
            $this->ctManageFee        = '';
            $this->ctSponsorshipFee   = '';
            $this->ctPromotionFee     = '';
            $this->ctOtherFee         = '';
            $this->expenseDifferDesc  = '';
            $this->leaseFiles         = '';
            $this->transferFee        = '';
            $this->ctSubmitTime       = 0;
        }
        return $this->save();
    }

    public function setStatusFail(int $uid)
    {
        $this->status              = SiteLocationEnum::STATUS_2;
        $this->siteStatus          = OpenShopSiteLocationModel::SITE_STATUS_3;
        $this->handler             = $this->developConsultantId;
        $this->houseEvaluateStatus = SiteLocationEnum::HOUSE_EVALUATE_STATUS_WAIT;
        $this->updatedByUid        = $uid;
        return $this->save();
    }

    public function setStatusPending(int $uid, $status, $superAdmin)
    {
        $this->siteStatus   = $status;
        $this->updatedByUid = $uid;
        $this->handler      = implode(',', $superAdmin);
        return $this->save();
    }


    public function setHandler(array $userIds)
    {
        $this->handler = implode(',', $userIds);
        return $this->save();
    }

    public function locationRel()
    {
        return $this->hasOne(OpenShopLocationModel::class, 'orderNo', 'orderNo');
    }

    public function baseUserInfoRel()
    {
        return $this->hasOne(OpenShopUserBaseInfoModel::class, 'orderNo', 'orderNo');
    }

    public function baseUserContractRel()
    {
        return $this->hasOne(OpenShopUserContractModel::class, 'orderNo', 'orderNo');
    }


    public function identityCardRel(): HasOne
    {
        return $this->hasOne(
            OpenShopUserIdentityCardModel::class,
            'orderNo',
            'orderNo',
        );
    }

    public function orderManagerRel()
    {
        return $this->hasMany(OpenShopOrderManagerModel::class, 'mainProcessId', 'mainProcessId');
    }

    /**
     * @return HasMany
     */
    public function attachRel(): HasMany
    {
        return $this->hasMany(OpenShopUploadFileResourceModel::class, "orderNo", "orderNo");
    }

    public function uploadFileResourceRel()
    {
        return $this->hasMany(OpenShopUploadFileResourceModel::class, 'orderNo', 'orderNo');
    }

    /**
     * @return HasOne
     */
    public function userContractRel(): HasOne
    {
        return $this->hasOne(OpenShopUserContractModel::class, 'orderNo', 'orderNo');
    }

    /**
     * @return HasOne
     */
    public function openShopMainProcessRel(): HasOne
    {
        return $this->hasOne(OpenShopMainProcessModel::class, 'orderNo', 'orderNo');
    }

    public function houseEvaluateRel(): HasOne
    {
        return $this->hasOne(OpenShopSiteLocationHouseEvaluateModel::class, 'orderNo', 'orderNo');
    }

    /**
     * @param string $orderNo
     * @return Builder|Model|object|null
     */
    public static function detailByOrderNo(string $orderNo)
    {
        return self::query()->where("orderNo", $orderNo)->first();
    }

    /**
     * 将查询作用域限制为仅包含给定类型的用户
     *
     * @param \Illuminate\Database\Eloquent\Builder $query
     * @param mixed $type
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function scopeOfSiteLocaltion($query, $provinceChief, $userId, $userInfo)
    {
        return $query
            ->where(function ($query) use ($provinceChief, $userId) {
                $query->whereRaw('1');
                $query->when($userId, function ($query) use ($userId) {
                    $query->where('developConsultantId', $userId)
                          ->orWhere('createdByUid', $userId);
                })
                      ->when(count($provinceChief), function ($query) use ($provinceChief) {
                          $query->whereIn('provinceCode', $provinceChief);
                      });
            })
            ->orWhere(function ($query) use ($userInfo) {
                $query->where('createdByUid', $userInfo->userId);
            });
    }

    public function scopeOfDevelop($query, $userId)
    {
        return $query->where('developConsultantId', $userId)
                     ->orWhere('createdByUid', $userId);
    }

    //定义一个访问器
    public function getMallStatusAttribute($value): bool
    {
        return (bool)$value;
    }

    //定义一个修改器
    public function setMallStatusAttribute($value)
    {
        $this->attributes['mallStatus'] = (bool)$value;
    }

    //定义一个访问器
    public function getIsWhiteListAttribute($value): bool
    {
        return (bool)$value;
    }

    //定义一个修改器
    public function setIsWhiteListAttribute($value)
    {
        $this->attributes['isWhiteList'] = (bool)$value;
    }

    /**
     * 获取点位的名称
     *
     * @param int $placeholderId
     * @return mixed
     */
    public static function getShopNameByIdNearByPlaceholderId(int $placeholderId = 0): string
    {
        return Cache::remember('getShopNameByIdNearByPlaceholderId:' . $placeholderId, getSwitchCacheTime(3600),
            function () use ($placeholderId) {
                $nearbyPlaceHolderName = '';
                if ($placeholderId) {
                    $orderNo               = (string)OpenShopSiteLocationModel::where('id', $placeholderId)
                                                                              ->value('orderNo');
                    $signOrderInfo         = (new SignOrderService($orderNo, null, true, true))->getSignOrder();
                    $nearbyPlaceHolderName = ShopService::getShopNameByCode($signOrderInfo->shopCode) ?? '';
                }

                return $nearbyPlaceHolderName;
            });
    }

    /**
     * 首页查询条件构造
     *
     * @param int $regionSelectionType
     * @param string $region
     * @param string $regionValue
     * @return Builder|mixed
     */
    public static function buildHomeSearchQuery(int $regionSelectionType, string $region, string $regionValue)
    {
        $query = function ($query) {
            $query->where("id", 0);
        };
        switch ($regionSelectionType) {
            case HomeService::REGION_SELECTION_TYPE_1:
                $region = attributeGet(
                    OpenShopOrganizationManageModel::allOrganizationManage()
                                                   ->where("type", "<>",
                                                       OpenShopOrganizationManageModel::HEADQUARTERS_ID)
                                                   ->where("name", $region)
                                                   ->first(),
                    "regionRel",
                    collect([])
                );

                if ($provinceCodes = $region->pluck("provinceCode")->toArray()) {
                    $query = function ($query) use ($provinceCodes) {
                        return $query->whereIn("provinceCode", $provinceCodes);
                    };
                }
                break;
            case HomeService::REGION_SELECTION_TYPE_2:
                $query = function ($query) use ($regionValue) {
                    return $query->where("provinceCode", $regionValue);
                };
                break;
            case HomeService::REGION_SELECTION_TYPE_3:
                $query = function ($query) use ($regionValue) {
                    return $query->where("cityCode", $regionValue);
                };
                break;
            case HomeService::REGION_SELECTION_TYPE_0:
                $query = null;
                break;
        }
        return self::query()->when($query, function ($subQuery) use ($query) {
            return $subQuery->where($query);
        });
    }

    public function relationWangguiRel()
    {
        return $this->hasOne(OpenShopSiteLocationWangguiRelationModel::class, 'siteId', 'id');
    }
}
